<template>
  <el-form ref="roleRuleFormRef" v-model="roleRuleForm" label-width="auto" :inline="true">
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model.trim="roleRuleForm.roleName" placeholder="请输入角色名称" />
    </el-form-item>
    <el-button type="primary" @click="submitForm(roleRuleFormRef)">
      查询
    </el-button>
    <el-button @click="resetForm(roleRuleFormRef)">重置</el-button>

  </el-form>
  <div>
    <el-button type="primary" @click="handleCreate">创建</el-button>

  </div>
  <div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column :label="item.label" :prop="item.property" :formatter="item.formatter"
        v-for="(item, t) in columns" :key="t" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)" v-has="'user-edit'">编辑</el-button>
          <el-button type="primary" @click="setPermission(scope.row)">设置权限</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-has="'user-delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="demo-pagination-block">
    <div class="demonstration">All combined</div>
    <el-pagination v-model:current-page="pager.currentPage" v-model:page-size="pager.pageSize"
      :page-sizes="[1, 3, 5, 7, 10]" :size="size" :disabled="disabled" :background="background"
      layout="total, sizes, prev, pager, next, jumper" :total="pager.total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 对话框1，角色设置 -->
  <el-dialog v-model="dialogVisible" :title="active == 'create' ? '创建' : '编辑'" width="35%" draggable
    @close="closeDialog">
    <div>
      <el-form ref="DialogRuleFormRef" style="max-width: 600px" :model="DialogRuleForm" :rules="rules"
        label-width="auto">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="DialogRuleForm.roleName" placeholder="请输入您的角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="DialogRuleForm.remark" placeholder="请输入您的备注" />
        </el-form-item>

      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="operateForm(DialogRuleFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 对话框2，权限设置 -->
  <el-dialog v-model="permissionDialogVisible" :title="'权限设置'" width="35%" draggable @close="closeDialog">
    <div class="pb-4">角色名称：{{ rolename }}</div>
    <div>
      <el-tree ref="treeRef" style="max-width: 600px" :data="roleData" show-checkbox node-key="_id" default-expand-all
        :props="defaultProps" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="permissionRoleoperateForm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import Api from './../api/index';
import { ElMessage, ElMessageBox } from 'element-plus'



//form
const roleRuleFormRef = ref<FormInstance>()
const roleRuleForm = reactive<RuleForm>({
  roleName: '',
  remark: ''
})
//获取表单列表数据
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  getRoleList()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// user操作按钮
const dialogVisible = ref(false)
const active = ref('add')
//新增
const handleCreate = () => {
  dialogVisible.value = true
  active.value = 'create'
}

//设置权限 
let rolename = ref()
let currentId = ref()
const setPermission = (row: any) => {
  console.log(row);
  let { checkKeys } = row.permissionList
  rolename.value = row.roleName
  currentId.value = row._id
  setTimeout(() => {
    treeRef.value.setCheckedKeys(checkKeys, false)
  }, 20)
  permissionDialogVisible.value = true
}
//编辑
const handleEdit = (row: User) => {
  console.log(row)
  active.value = 'edit'
  // 这里需要用异步处理一下，避免bug
  nextTick(() => {
    // 把数据整合，使点击编辑可以拿到该数据
    Object.assign(DialogRuleForm, row)
  })
  dialogVisible.value = true
}

//对话框2 ，权限设置
let treeRef = ref()
const permissionDialogVisible = ref(false)
const permissionRoleoperateForm = () => {
  let nodes = treeRef.value.getCheckedNodes()  //选中的是全选的按钮或者菜单
  let halfkeys = treeRef.value.getHalfCheckedNodes()    //半选中的菜单
  let checkKeys: any = []//按钮的ID
  let parentKeys: any = []//全选中的菜单的ID
  // 区分处理全选节点
  nodes.forEach((node: any) => {
    // 判断是否为叶子节点（没有children属性或children为空数组）
    if (!node.children || node.children.length === 0) {
      checkKeys.push(node._id)  // 叶子节点（按钮）放入checkKeys
    } else {
      parentKeys.push(node._id) // 父节点（菜单）放入parentKeys
    }
  })
  // 处理半选节点
  let halfCheckedKeys: any = []
  halfkeys.map((node: roleRootObject) => {
    halfCheckedKeys.push(node._id)
  })
  let params = {
    _id: currentId.value,
    permissionList: {
      checkKeys: checkKeys,//全选 按钮
      halfCheckedKeys: halfCheckedKeys.concat(parentKeys)//半选 菜单
    },
  }
  Api.setPermissionList(params).then((res: any) => {
    console.log(res);
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '设置成功',
      })
      
    }
    getRoleList();
    permissionDialogVisible.value = false
  })
}
const defaultProps = {
  children: 'children',
  label: 'menuName',
}
const roleData = ref([])




//单个删除处理
const handleDelete = (row: any) => {
  console.log(row)
  ElMessageBox.confirm(
    '你确定要删除这个数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Api.getRoleDeleteListAPI({ _id: row._id }).then((res) => {
        if (res) {
          getRoleList()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//关闭表单重置表单信息
const closeDialog = () => {
  resetForm(DialogRuleFormRef.value)
}
const tableData = ref<User[]>([])

//获得二级菜单并做字典映射
const actionValue = ref<any>({})
const getActionMap = (list: any) => {
  actionValue.value = {}; // 清空旧数据
  const deep = (data: any) => {
    data.forEach((item: any) => {
      // 仅当当前节点有children时（说明是二级菜单的父级）
      if (item.children && item.children.length > 0) {
        // 只处理二级菜单节点
        item.children.forEach((child: any) => {
          actionValue.value[child._id] = child.menuName;
        });
      }
      // 保持递归调用
      if (item.children && item.children.length > 0) {
        deep(item.children);
      }
    });
  };
  deep(JSON.parse(JSON.stringify(list)));
};
//表格列
const columns = [{
  label: '角色名称',
  property: 'roleName',
  width: '100px'
},
{
  label: '备注',
  property: 'remark'
},
{
  label: '权限列表',
  property: 'permissionList',
   formatter: function (_row: any, _columns: any, cellValue: any, _index: any) {
    if (!cellValue) return '';
    const { halfCheckedKeys } = cellValue;
    // 确保是数组
    if (!Array.isArray(halfCheckedKeys)) return '';
    const names: string[] = [];
    halfCheckedKeys.forEach((key: any) => {
      // 直接从映射中获取菜单名称
      const name = actionValue.value[key];
      if (name) {
        names.push(name);
      }
    });
    
    return names.join(", ");
  }
},
{
  label: '更新时间',
  property: 'updateTime'
},
{
  label: '创建时间',
  property: 'createTime'
},

]

//分页
import type { ComponentSize } from 'element-plus'
const pager = ref({
  currentPage: 1,
  pageSize: 10,
  total: 10
})
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

// 分页大小变化
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pager.value.pageSize = val
  getRoleList()
}
//分页页数变化
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  pager.value.currentPage = val
  getRoleList()
}

//对话框表单
const DialogRuleFormRef = ref<FormInstance>()
const DialogRuleForm = reactive<DialogRuleForm>({
  roleName: '',
  remark: ''
})
//角色的新增或编辑，连接后端
const operateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate()
  let params: any = DialogRuleForm
  params.active = active.value
  Api.getRoleOperateListAPI(params).then(res => {
    if (res) {
      dialogVisible.value = false
      getRoleList()
    }
  })

};


//表单验证规则
const rules = reactive<FormRules<DialogRuleForm>>({
  roleName: [
    { required: true, message: '请输入角色名', trigger: 'blur' },
    { min: 2, max: 10, message: '角色名长度为2-10之间', trigger: 'blur' },
  ],

})

//请求
//角色数据请求
const getRoleList = async () => {
  const params = {
    ...roleRuleForm,
    ...pager.value
  }
  const res: any = await Api.getRolesListAPI(params);
  console.log("user", res);
  const { list, total } = res
  tableData.value = list
  pager.value.total = total
}

//菜单数据请求
const getMenuList = async () => {
  const res: any = await Api.getMenuListAPI();
  // console.log("res", res);
  roleData.value = res;
  getActionMap(res)
};

onMounted(() => {
  getRoleList()
  getMenuList();
})
</script>

<style>
.el-select__input-wrapper.is-hidden {
  position: initial;
}
</style>